#!/bin/bash
# 启动所有微服务的脚本

echo "=========================================="
echo "员工事务管理系统 - 服务启动脚本"
echo "=========================================="
echo ""

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "❌ 未找到Java，请先安装JDK 1.8+"
    exit 1
fi

echo "✅ Java环境检查通过"
echo ""

# 检查Maven环境
if ! command -v mvn &> /dev/null; then
    echo "❌ 未找到Maven，请先安装Maven"
    exit 1
fi

echo "✅ Maven环境检查通过"
echo ""

# 检查Nacos
if ! lsof -i :8848 &> /dev/null; then
    echo "⚠️  Nacos未运行（端口8848）"
    echo "   请先启动Nacos: sh startup.sh -m standalone"
    echo "   或访问: https://nacos.io/zh-cn/docs/quick-start.html"
    echo ""
fi

# 检查RocketMQ
if ! lsof -i :9876 &> /dev/null; then
    echo "⚠️  RocketMQ未运行（端口9876）"
    echo "   请先启动RocketMQ NameServer和Broker"
    echo "   或访问: https://rocketmq.apache.org/docs/quick-start/"
    echo ""
fi

echo "=========================================="
echo "开始启动微服务..."
echo "=========================================="
echo ""
echo "提示：每个服务会在新终端窗口启动"
echo "请确保Nacos和RocketMQ已启动"
echo ""
read -p "按回车键继续，或Ctrl+C取消..."

# 获取项目根目录
PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"

# 启动函数
start_service() {
    local service_name=$1
    local service_dir=$2
    local port=$3
    
    echo ""
    echo "启动 $service_name (端口: $port)..."
    cd "$PROJECT_ROOT/$service_dir"
    
    # macOS使用osascript打开新终端
    if [[ "$OSTYPE" == "darwin"* ]]; then
        osascript -e "tell application \"Terminal\" to do script \"cd '$PROJECT_ROOT/$service_dir' && mvn spring-boot:run\""
    else
        # Linux使用gnome-terminal或xterm
        gnome-terminal -- bash -c "cd '$PROJECT_ROOT/$service_dir' && mvn spring-boot:run; exec bash" 2>/dev/null || \
        xterm -e "cd '$PROJECT_ROOT/$service_dir' && mvn spring-boot:run" 2>/dev/null || \
        echo "请手动在新终端执行: cd $service_dir && mvn spring-boot:run"
    fi
    
    sleep 3
}

# 按顺序启动服务
start_service "网关服务" "gateway-service" "8080"
start_service "认证服务" "auth-service" "8081"
start_service "用户服务" "user-service" "8082"
start_service "考勤服务" "attendance-service" "8083"
start_service "请假服务" "leave-service" "8084"
start_service "薪资服务" "salary-service" "8085"
start_service "通知服务" "notification-service" "8086"

echo ""
echo "=========================================="
echo "✅ 所有服务启动命令已执行"
echo "=========================================="
echo ""
echo "服务端口："
echo "  - Gateway: 8080"
echo "  - Auth: 8081"
echo "  - User: 8082"
echo "  - Attendance: 8083"
echo "  - Leave: 8084"
echo "  - Salary: 8085"
echo "  - Notification: 8086"
echo ""
echo "请检查各个终端窗口，确保服务启动成功"
echo "访问前端: http://localhost:3000"
echo ""

